package cn.lxg.controller.common;

import cn.lxg.pojo.TAdmin;
import cn.lxg.pojo.TUser;
import cn.lxg.service.IAdminService;
import cn.lxg.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/page")
public class LoginController {
    @Autowired
    private final IAdminService adminService = null;

    @Autowired
    private final IUserService userService = null;

    @GetMapping(value = "/login")
    public String loginPage(HttpSession session) {
        session.removeAttribute("admin");
        session.removeAttribute("user");
        return "common/login";
    }

    @PostMapping(value = "/admin/login")
    public String adminLogin(HttpSession session, Model model, TAdmin admin) {
        // 准备数据
        String msg = this.adminService.login(admin);

        // 登录失败
        if (!"OK".equals(msg)) {
            // 传输数据给前端
            model.addAttribute("msg", msg);

            return "common/message";
        }

        // 登录成功
        session.setAttribute("admin", admin);

        model.addAttribute("msg", "登录成功");
        return "common/message";
    }

    @PostMapping(value = "/user/login")
    public String userLogin(HttpSession session, Model model, TUser user) {
        // 准备数据
        String msg = this.userService.login(user);

        // 登录失败
        if (!"OK".equals(msg)) {
            // 传输数据给前端
            model.addAttribute("msg", msg);

            return "common/message";
        }

        // 登录成功
        session.setAttribute("user", user);

        model.addAttribute("msg", "登录成功");
        return "common/message";
    }
}
